package com.ygglxt.servlet;

import com.google.gson.Gson;
import com.ygglxt.entity.Admin;
import com.ygglxt.service.AdminService;
import com.ygglxt.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理登录Servert
 */
@WebServlet(name = "AdminServlet",urlPatterns = "/AdminServlet")
public class AdminServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //这里类型要设置未text/json
        response.setContentType("text/json;charset=utf-8");
        AdminService adminService=new AdminService();
        String method= request.getParameter("method");
        if(method.equals("login")){
            String account=request.getParameter("account");
            String pwd=request.getParameter("pwd");
            List<Object> objects=new ArrayList<>();
            objects.add(account);
            objects.add(pwd);
            Admin admin=adminService.login(objects);
            //将当前用户信息转化为json传回给前端（用的JSON的转化方法）
            PrintWriter writer = response.getWriter();
            if(admin!=null){//登录成功
                request.getSession().setAttribute("admin",admin);
                writer.write(new Gson().toJson(Result.reOk("登录成功")));
            }else{//账号密码错误
                writer.write(new Gson().toJson(Result.reError("账号密码错误")));
            }
        }else if(method.equals("get")){
            //将当前用户信息转化为json传回给前端（用的JSON的转化方法）
            PrintWriter writer = response.getWriter();
            if(request.getSession().getAttribute("admin")!=null){
                Admin admin=(Admin)request.getSession().getAttribute("admin");
                writer.write(new Gson().toJson(Result.reOk("",admin)));
            }else{
                writer.write(new Gson().toJson(Result.reError("登录已过期，请重新登录")));
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request,response);
    }


}
